/**
 * @description 判断是否是数组
 * @param  {Array} arr 数据
 * @return {Boolean} true 原数组 false []
 */
function getArrData(arr) {
    var flag = Array.isArray(arr) && arr.length
    return flag ? arr : []
}

/**
 * @description 判断是否为空 兼容数组 字符串 对象
 * @param  {Object} obj 对象
 * @return {Boolean} true 为空 false 不为空
 */
function isEmpty(obj) {
    // 本身为空直接返回true
    if (obj === null || obj === 'null' || obj === 'undefined') return true

    // 本身未定义直接返回true
    if (typeof obj === 'undefined') return true

    // 根据长度判断。
    if (JSON.stringify(obj) === '{}') return true
    if (obj.length > 0) return false
    if (obj.length === 0) return true

    // 用变量保存可以加速对对象原型的hasOwnProperty的访问。
    var hasOwnProperty = Object.prototype.hasOwnProperty
    // 通过属性长度判断
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false
    }

    return false
}

/**
 * @description 判断不为空 兼容数组 字符串 对象
 * @param  {Object} obj 对象
 * @return {Boolean} true 不为空 false 为空
 */
function isNotEmpty(obj) {
    return !isEmpty(obj)
}

/**
 * @description 深拷贝对象到一个新对象 子节点不进行拷贝
 * @param  {Object} obj 对象
 */
function cloneData(obj, pamarmName = null) {
    let newObj = {}
    if (!obj) {
        return newObj
    }
    for (let i in obj) {
        if (i !== 'children' && i !== pamarmName) newObj[i] = Vue.prototype.$cloneDeep(obj[i])
    }

    return newObj
}

/**
 * @description 判断字符串是否为json格式
 * @param  {Object} jsonVal 对象
 */
function checkJson(jsonVal, isLog = true) {
    try {
        var obj = JSON.parse(jsonVal)
        return typeof obj === 'object' && obj
    } catch (ex) {
        if (isLog) log.error(ex + ' json：' + jsonVal)
        return false
    }
}

// 获取链接地址参数
function queryUrlParams(pageUrl) {
    let obj = {} // 声明参数对象
    if (isEmpty(pageUrl)) {
        return obj
    }

    let url = pageUrl.split('?')[1]
    if (isEmpty(url)) {
        return obj
    }

    let arr = url.split('&') // 以&符号分割为数组
    for (let i = 0; i < arr.length; i++) {
        let arrNew = arr[i].split('=') // 以"="分割为数组
        obj[arrNew[0]] = arrNew[1]
    }
    return obj
}

// 对象key转为小写
function objToLowerCase(objData) {
    if (isEmpty(objData)) {
        return objData
    }

    for (var key in objData) {
        if (Object.prototype.hasOwnProperty.call(objData, key)) {
            var lowerkey = key.toLowerCase()
            if (lowerkey !== key) {
                // 赋给新的属性标识，删除旧的
                objData[lowerkey] = objData[key]
                delete objData[key]
            }
        }
    }
    return objData
}

// 字符串数据为空或者undefined时返回''
function dataIsNull(data) {
    var strData = ''
    if (isNotEmpty(data)) {
        strData = data
    }
    return strData
}

// 获取窗口正常显示高度
function modalClientStyle(num = 0) {
    return {
        height: document.body.clientHeight - 102 - num + 'px',
        overflow: 'auto'
    }
}

// 判断数组是否相等
function ArrayisEquals(arr1, arr2) {
    return (
        arr1.length === arr2.length &&
        arr1.every(function (v, i) {
            return v === arr2[i]
        })
    )
}

// 验证标识是否符合规范
function validateName(rule, value, callback) {
    if (/^[A-Za-z0-9_]{2,32}$/g.test(value)) {
        callback()
    } else {
        return callback(new Error('只能包含英文、数字和下划线'))
    }
}

// 全局错误提示
function msgError(content) {
    Vue.prototype.$Message.destroy()
    Vue.prototype.$Message.error({
        content: content,
        duration: 10,
        closable: true
    })
}

// 全局验证移除表单提交中的前后空格
function dataTrim(obj) {
    if (isEmpty(obj)) {
        return obj
    }

    let newObj = Array.isArray(obj) ? [] : {}

    for (let key in obj) {
        // 属性是obj直接属性，非继承属性
        if (Object.hasOwnProperty.call(obj, key)) {
            let value = obj[key]
            if (typeof value === 'object' && value !== null) {
                newObj[key] = dataTrim(value)
            } else if (typeof value === 'string' && getJsonPaseStr(value)) {
                let newData = value.trim()
                newObj[key] = newData && newData.length > 255 ? newData : escapeHtml(newData)
            } else {
                newObj[key] = value
            }
        }
    }
    return newObj
}

// 验证数据是否字符串
function getJsonPaseStr(str) {
    if (checkJson(str, false)) {
        let newStr = JSON.parse(str)
        return typeof newStr === 'string'
    }
    return true
}

// 转义html代码中的特殊字符
function escapeHtml(str) {
    const escapeMap = {
        '<': '%3C',
        '>': '%3E'
    }

    return str.replace(/[<>]/g, function (match) {
        return escapeMap[match]
    })
}

// 删除记录
function deleteRecord(title, nameStr, callback) {
    Vue.prototype.$Modal.confirm({
        title: '删除' + title,
        content: `<p>确认删除${title}${nameStr ? '：' + nameStr + ' ' : nameStr}吗?</p>`,
        onOk: () => callback()
    })
}

// 设置全屏
function setFullScreen(isAlwayFullScreen = false) {
    let result = 'unsupported'
    var elem = document.body
    if (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled) {
        if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
            if (isAlwayFullScreen) return
            if (document.exitFullscreen) {
                document.exitFullscreen()
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen()
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen()
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen()
            }

            this.$store.state.pageIsFullScreen = false
            log.primary('========  Exit FullScreen')
            result = 'exit'
        } else {
            if (elem.requestFullscreen) {
                elem.requestFullscreen()
            } else if (elem.webkitRequestFullscreen) {
                elem.webkitRequestFullscreen()
            } else if (elem.mozRequestFullScreen) {
                elem.mozRequestFullScreen()
            } else if (elem.msRequestFullscreen) {
                elem.msRequestFullscreen()
            }

            this.$store.state.pageIsFullScreen = true

            log.primary('========  FullScreen')
            result = 'fullScreen'
        }
    } else {
        log.error('Fullscreen is not supported on your browser.')
    }
    return result
}

// 百度坐标转高德（传入经度、纬度）
function bdToGeoLngLat(bdLng, bdLat) {
    var X_PI = (Math.PI * 3000.0) / 180.0
    var x = bdLng - 0.0065
    var y = bdLat - 0.006
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI)
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI)
    var ggLng = z * Math.cos(theta)
    var ggLat = z * Math.sin(theta)
    return [ggLng, ggLat]
}

// 高德坐标转百度（传入经度、纬度）
function geoToBdLnglat(lng, lat) {
    var X_PI = (Math.PI * 3000.0) / 180.0
    var x = lng
    var y = lat
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI)
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI)
    var bdLng = z * Math.cos(theta) + 0.0065
    var bdLat = z * Math.sin(theta) + 0.006
    return [bdLng, bdLat]
}

/**
 * 触发 window.resize
 */
function triggerWindowResizeEvent() {
    const event = document.createEvent('HTMLEvents')
    event.initEvent('resize', true, true)
    event.eventType = 'message'
    window.dispatchEvent(event)
}

// 是否IE浏览器
function isIE() {
    const bw = window.navigator.userAgent
    const compare = s => bw.indexOf(s) >= 0
    const ie11 = (() => 'ActiveXObject' in window)()
    return compare('MSIE') || ie11
}

// 获取随机字符串
function generateRandomStr(len, charSet) {
    const chars = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let randomStr = ''
    for (var i = 0; i < len; i++) {
        randomStr += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return randomStr
}

// 设备状态
function statusMap() {
    return {
        0: {
            status: 'init',
            text: '初始化',
            color: '#2D8CF0'
        },
        1: {
            status: 'normal',
            text: '正常',
            color: '#20cf51'
        },
        2: {
            status: 'alarm',
            text: '报警',
            color: '#E34D59'
        },
        3: {
            status: 'offline',
            text: '断开连接',
            color: '#F1CD00'
        },
        4: {
            status: 'free',
            text: '空闲',
            color: '#BFBFBF'
        }
    }
}

function messageTypeMap() {
    return {
        0: {
            text: '系统'
        },
        1: {
            text: '安全'
        },
        2: {
            text: '设备'
        },
        3: {
            text: '设备属性'
        },
        4: {
            text: '设备指令'
        },
        5: {
            text: '设备事件'
        },
        9: {
            text: '设备上线'
        },
        10: {
            text: '设备离线'
        },
        200: {
            text: '算法识别'
        },
        1000: {
            text: '门禁事件'
        },
        2000: {
            text: '人脸识别'
        },
        3000: {
            text: '停车场事件'
        },
        3001: {
            text: '岗亭呼叫'
        },
        4000: {
            text: '消防事件'
        },
        4001: {
            text: '设备拆除'
        },
        4002: {
            text: '烟雾告警'
        },
        4003: {
            text: '手动火灾报警'
        },
        4004: {
            text: '水压告警'
        },
        4005: {
            text: '液位告警'
        },
        4006: {
            text: '电气火灾'
        }
    }
}

function messageLevelMap() {
    return {
        0: {
            text: '调试',
            type: 'debug',
            icon: 'ios-information-circle',
            color: '#2db7f5'
        },
        1: {
            text: '消息',
            type: 'info',
            icon: 'ios-information-circle',
            color: '#2db7f5'
        },
        2: {
            text: '警告',
            type: 'warning',
            icon: 'md-warning',
            color: '#faad14'
        },
        3: {
            text: '错误',
            type: 'error',
            icon: 'md-close-circle',
            color: '#f50'
        },
        4: {
            text: '故障',
            type: 'fault',
            icon: 'md-close-circle',
            color: '#f50'
        }
    }
}

function AssetStatusMap() {
    return {
        1: {
            status: 'success',
            text: '正常',
            color: '#87d068'
        },
        2: {
            status: 'error',
            text: '异常',
            color: '#ff5500'
        },
        3: {
            status: 'default',
            text: '未知',
            color: '#d9d9d9'
        }
    }
}

// 工单状态含义
function getOrderState(state) {
    var result = ''
    switch (state) {
        case 0:
            result = '待处理'
            break
        case 1:
            result = '处理中'
            break
        case 2:
            result = '已处理'
            break
        case 3:
            result = '已完成'
            break
    }
    return result
}

// 工单级别含义
function getOrderLevelText(level) {
    var result = ''
    switch (level) {
        case 0:
            result = '每日'
            break
        case 1:
            result = '每周'
            break
        case 2:
            result = '每月'
            break
        case 3:
            result = '每年'
            break
        case 4:
            result = '一次'
            break
    }
    return result
}

// 巡检计划-循环模式含义
function getLoopTypeText(loopType) {
    var result = ''
    switch (loopType) {
        case 0:
            result = '一般'
            break
        case 1:
            result = '中等'
            break
        case 2:
            result = '紧急'
            break
    }
    return result
}

function JsonParse(data) {
    if (isNotEmpty(data)) {
        return JSON.parse(data)
    }

    return {}
}

function loadJs(src) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.onload = () => {
            resolve()
        }
        script.onerror = err => {
            reject(err)
        }
        script.src = src
        document.getElementsByTagName('body')[0].appendChild(script)
    })
}

function base64ToFile(urlData, fileName) {
    // base64转成file文件
    const arr = urlData.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bytes = atob(arr[1]) // 解码base64
    let n = bytes.length
    const ia = new Uint8Array(n)
    while (n--) {
        ia[n] = bytes.charCodeAt(n)
    }
    return new File([ia], fileName, { type: mime })
}

// 生成4位随机数
function uuid4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}

// 生成8位随机数
function uuid8() {
    return uuid4() + uuid4()
}

// 生成16位随机数
function uuid16() {
    return uuid4() + uuid4() + uuid4() + uuid4()
}

// 对数组进行分组
function groupBy(array, f) {
    const groups = {}
    array.forEach(function (o) {
        const group = f(o)
        groups[group] = groups[group] || []
        groups[group].push(o)
    })

    let deviceList = []
    Object.keys(groups).forEach(group => {
        var objInfo = {}
        objInfo.name = group || '其他'
        objInfo.nodeType = 'group'
        let propertyList = groupByList(groups[group], function (item) {
            return [item.name] // 按照name进行分组
        })
        objInfo.children = propertyList
        deviceList.push(objInfo)
    })
    return deviceList
}

// 对数组进行二次分组
function groupByList(array, f) {
    const groups = {}
    array.forEach(function (o) {
        // 注意这里必须是forEach 大写
        const group = f(o)
        groups[group] = groups[group] || []
        groups[group].push(o)
    })
    let propertyList = []
    Object.keys(groups).forEach(group => {
        let list = groups[group]
        if (list && list.length > 0) {
            propertyList.push(list[0])
        }
    })
    return propertyList
}

// 获取属性enum类型值标签中文
function getValueLabelName(prop) {
    var result = 0
    if (prop.dataType === 'enum') {
        var item = prop.valueLables.find(item => parseInt(item.value) === parseInt(prop.value))
        if (item) {
            result = item.label
        }
    } else {
        result = isEmpty(prop.value) ? 0 : prop.value
    }
    return result
}

// 日期加减获得天数
// date1：开始日期，date2结束日期
function getNumberOfDays(date1, date2) {
    var a1 = Date.parse(new Date(date1))
    var a2 = Date.parse(new Date(date2))
    var day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24)) // 核心：时间戳相减，然后除以天数
    return day
}

// 标准日期时间
function dateTimeFormat(dateTime) {
    // 格式化时间
    var dateParse = Date.parse(new Date(dateTime)) // 转成时间戳
    var time = new Date(dateParse) // 再转成标准时间
    var y = String(time.getFullYear())
    var m = String(time.getMonth() + 1)
    var d = String(time.getDate())
    var h = String(time.getHours())
    var u = String(time.getMinutes())
    var s = String(time.getSeconds())
    return { y, m, d, h, u, s }
    // return m+"/"+d//直接输入自己想要的格式
}

// 获取几天前的时间
function getDay(day) {
    function doHandleMonth(month) {
        var m = month
        if (month.toString().length === 1) {
            m = '0' + month
        }
        return m
    }
    var today = new Date()
    var targetdayMilliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
    today.setTime(targetdayMilliseconds) // 注意，这行是关键代码
    var tYear = today.getFullYear()
    var tMonth = today.getMonth()
    var tDate = today.getDate()
    tMonth = doHandleMonth(tMonth + 1)
    tDate = doHandleMonth(tDate)
    return tYear + '-' + tMonth + '-' + tDate
}

// 页面跳转
function pageJump(val, authCheck = false) {
    if (authCheck) {
        var result = Vue.prototype.$common.menu.getMenuByPath(val)
        if (isNotEmpty(result)) {
            router.app.$router.push({
                path: val
            })
        } else {
            msgError('用户无权限访问此页面')
        }
    } else {
        router.app.$router.push({
            path: val
        })
    }
}

// 获取signalr分组名称 依据pathname判定
function getSignalrGroup() {
    let pathname = location.pathname
    return pathname && pathname === '/' ? 'iothub' : pathname.substring(1, pathname.length - 1)
}

// 关闭signalr
function closeSignalr() {
    removeSignalr(Vue.prototype.signalr)
    removeSignalr(Vue.prototype.gatewayHub)
}

// 移除指定signalr
function removeSignalr(signal) {
    if (signal && signal.state === 1) {
        // 将连接从指定分组移除
        signal.stop()
    }
}

// 事件内容数组转字符串格式
function getMessageContent(content) {
    let messageContent = ''
    if (isNotEmpty(content) && Object.prototype.toString.call(content) === '[object Array]') {
        content.forEach(x => {
            messageContent += x.content + '\n'
        })
    }
    return messageContent
}

// 获取场所地址
function getPlaceAddress(placeAddresse) {
    let result = ''
    if (isNotEmpty(placeAddresse)) {
        if (placeAddresse.includes('addressLeft') && checkJson(placeAddresse)) {
            // 将地址转成对象
            var addObj = JSON.parse(placeAddresse)
            result = isNotEmpty(addObj) ? addObj.addressLeft.join().replace(/,/g, '') + addObj.adddressRight : ''
        } else {
            result = placeAddresse
        }
    }

    return result
}

// 限制上传文件类型
function handleFormatErrorImg(file) {
    Vue.prototype.$Message.warning(file.name + '文件格式不正确,请选择jpg、jpeg或png')
}

function handleFormatErrorXlsx(file) {
    Vue.prototype.$Message.warning(file.name + '文件格式不正确,请选择xls或xlsx文件')
}
function handleFormatErrorDll(file) {
    Vue.prototype.$Message.warning(file.name + '文件格式不正确,请选择dll文件')
}
function handleFormatErrorMedia(file) {
    Vue.prototype.$Message.warning(file.name + '文件格式不正确,请选择MP3文件')
}

function handleFormatError(file) {
    Vue.prototype.$Message.msgError(file.name + '文件格式不正确,请选择txt、pdf、xls、xlsx、jpg、jpeg、png、dll、doc或docx文件')
}

// 限制上传文件大小
function handleMaxSize(file) {
    msgError(file.name + ' 文件太大,不超过2M')
}
// 限制上传文件大小 100M
function handleMaxSize100(file) {
    msgError(file.name + ' 文件太大,不超过100M')
}

// 重置事件派单的内容
function formatMessageOrderData(data) {
    let result = Vue.prototype.$cloneDeep(data)

    // 区分图片和文本
    var contentData = result.content
    if (isNotEmpty(contentData)) {
        result.imgContent = []
        result.textContent = []
        contentData.forEach(x => {
            if (x.contentType === 2 || x.contentType === 3) {
                result.imgContent.push(x)
            } else {
                result.textContent.push(x)
            }
        })
    }

    return result
}


// 把事件内容的图片上传到工单
function uploadWorkOrderImg(data, res) {
    var imgContentData = data.imgContent
    if (isNotEmpty(imgContentData)) {
        var urlImgList = []
        var base64ImgList = []
        imgContentData.forEach(x => {
            if (x.contentType === 2) {
                if (Array.isArray(x.content)) {
                    x.content = x.content.toString()
                }
                urlImgList.push(x.content)
            } else {
                // base64转url
                var fileInfo = base64ToFile(x.content, uuid8() + '.png')
                base64ImgList.push(fileInfo.name)

                const form = new FormData()
                form.append('file', fileInfo)
                // 上传图片到工单
                Vue.prototype.imageApi.uploadImageWorkOrder(form).then(res => {
                    if (res.code !== 0) {
                        msgError('事件指派工单时上传base64图片失败，原因' + res.msg)
                    }
                })
            }
        })
        if (isNotEmpty(urlImgList)) {
            // 事件派单时把图片传给工单
            submitWorkOrderImg(urlImgList, res, 'url')
        }
        if (isNotEmpty(base64ImgList)) {
            // 事件派单时把图片传给工单
            submitWorkOrderImg(base64ImgList, res, 'base64')
        }
    }
}
// 事件派单时把图片传给工单
function submitWorkOrderImg(list, data, type) {
    list.forEach(x => {
        var item = {
            name: type === 'base64' ? x : x.split('/')[1],
            path: type === 'base64' ? '/img/workOrder/' + data : '/' + x,
            type: '.' + x.split('.')[1],
            workOrderId: data.msg
        }
        Vue.prototype.workOrderApiV2.uploadFile(data.msg, item).then(res => {
            if (res.code !== 0) {
                msgError(`事件指派工单时上传图片失败，原因${res.Msg}`)
            }
        })
    })
}

// 格式化事件列表数据
function formatMessageTable(data) {
    var list = getArrData(data)

    if (isEmpty(list)) {
        return list
    }
    list.forEach(x => {
        // 获取事件关联的页面和视频
        getMessageDataPageAndVideo(x)

        if (isEmpty(x.content)) {
            return list
        }
        // 排序,图片方前面
        x.content = [...x.content].sort((a, b) => b.contentType - a.contentType)
        x.content.forEach(y => {
            // contentType内容类型 2是url 3是base64
            if (y.contentType === 2) {
                // 一条内容里有多张图片时按分号切割
                y.content = y.content.split(';')
                y.content.forEach(z => {
                    if (isNotEmpty(z)) {
                        z = z.startsWith('http') ? z : window.iotWebConfig?.iotUrl + '/' + z
                    }
                })
            }
        })
    })

    return list
}

function formatDate(dateString) {  
    if(!dateString){
        return ''
    }
    const date = new Date(dateString);  
  
    // 验证日期是否有效  
    if (isNaN(date.getTime())) {  
        throw new Error('Invalid date string');  
    }  
  
    // 获取年份、月份、日期、小时、分钟和秒  
    const year = date.getFullYear();  
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1  
    const day = String(date.getDate()).padStart(2, '0');  
    const hours = String(date.getHours()).padStart(2, '0');  
    const minutes = String(date.getMinutes()).padStart(2, '0');  
    const seconds = String(date.getSeconds()).padStart(2, '0');  
  
    // 拼接成目标格式  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;  
}  
// 获取事件关联的页面和视频
function getMessageDataPageAndVideo(x) {
    let linkedData = x.device && x.device.linkedData ? x.device.linkedData : {}
    if (linkedData) {
        // 关联视频
        x.roundVideo = linkedData.roundVideo ? linkedData.roundVideo.split(',') : []
        // 关联定位页面
        var locationPage = linkedData.locationPage ? linkedData.locationPage.substring(linkedData.locationPage.lastIndexOf(':') + 1, linkedData.locationPage.length) : ''
        if (locationPage) {
            let pageArr = locationPage.split(',')
            if (isNotEmpty(pageArr) && pageArr.length > 2) {
                x.page = '?topologyId=' + pageArr[0] + '&designType=local&scale=5&local&branch=' + Vue.prototype.$branchName + '&locationPage=' + pageArr[1] + ',' + pageArr[2]
            }
        }
    }
}
// 获取字符串长度
function getStrFullLength(str = '') {
    return str.split('').reduce((pre, cur) => {
        const charCode = cur.charCodeAt(0)
        if (charCode >= 0 && charCode <= 128) {
            return pre + 1
        }
        return pre + 2
    }, 0)
}

function getJobStatus(status) {
    switch (status) {
        case 0:
            return '已停止'
        case 1:
            return '运行中'
        case 2:
            return '已暂停'
        case 3:
            return '已完成'
        case 4:
            return '异常'
        default:
            return ''
    }
}

// 判断是不是浮点数，返回true和false
function isFloat(value) {
    return typeof value === 'number' && !isNaN(value) && !Number.isInteger(value)
}

// 判断是否告警类事件
function getEventType(res) {
    return res.level >= 2 && res.type >= 2 && res.type !== 4 && res.type !== 9
}

// 获取路径中的租户信息
function getTenantKeyByPath(tenantKey) {
    let pathname = location.pathname
    return pathname === '/' ? '' : pathname.substring(1, pathname.length - 1)
}

// 一维数组转二维数组
function convertTo2DArray(list, num) {
    let newDataList = []
    let current = 0
    for (let i = 0; i <= list.length - 1; i++) {
        if (i % num !== 0 || i === 0) {
            if (!newDataList[current]) {
                newDataList.push([list[i]])
            } else {
                newDataList[current].push(list[i])
            }
        } else {
            current++
            newDataList.push([list[i]])
        }
    }
    return [...newDataList]
}

// 验证选择框改变事件
function validateSelect(rule, value, callback) {
    if (isEmpty(value)) {
        callback(new Error('请选择'))
    } else {
        callback()
    }
}

// 自定义校验时间
function validateTime(rule, value, callback) {
    if (value) {
        return callback()
    } else {
        return callback(new Error('时间不能为空'))
    }
}

// 获取周几数组
function getWeekDateArrStr(weekDate) {
    if (isNotEmpty(weekDate)) {
        if (weekDate.indexOf(',') > -1) {
            let strValue = ''
            var arrObj = weekDate.split(',')
            for (let index = 0; index < arrObj.length; index++) {
                strValue += getWeekDateStr(arrObj[index]) + ','
            }
            if (strValue) {
                strValue = strValue.substring(0, strValue.length - 1)
            }
            return strValue
        } else {
            return getWeekDateStr(weekDate)
        }
    } else {
        return ''
    }
}

// 获取周几
function getWeekDateStr(value) {
    let str = ''
    if (isNotEmpty(value)) {
        switch (value.toLowerCase()) {
            case '1':
                str = '周一'
                break
            case '2':
                str = '周二'
                break
            case '3':
                str = '周三'
                break
            case '4':
                str = '周四'
                break
            case '5':
                str = '周五'
                break
            case '6':
                str = '周六'
                break
            case '0':
                str = '周日'
                break
            case '-1':
                str = '每天'
                break
        }
    }
    return str
}

// 获取字符或者数值类型的数据
function getPropValueToFixed(value) {
    if (value && String(value).includes('.')) {
        return parseFloat(value).toFixed(2)
    }
    return value
}

// 更新图表数据
function updateChartData(node) {
    node.elementRendered = false
    node.dataLoadFinish = true
    window.designCanvas.updateProps(node)
}

function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time))
}

// 移除对象中的空属性
function removeEmptyProperties(obj) {
    if (typeof obj === 'object' && isNotEmpty(obj)) {
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                const value = obj[key]
                if (isEmpty(value)) {
                    delete obj[key]
                }
            }
        }
    }

    return obj
}

function validatePhoneNumber(phoneNumber) {
    // 使用正则表达式验证手机号
    var regex = /^1[3456789]\d{9}$/
    return regex.test(phoneNumber)
}

function validateEmail(email) {
    // 使用正则表达式验证邮箱
    var regex = /^([a-zA-Z0-9_]-*\.*)+@([a-zA-Z0-9_]-?)+(\.[a-zA-Z]{2,3}){1,2}$/
    return regex.test(email)
}

function validateLongitude(longitude) {
    // 使用正则表达式验证经度
    var regex = /^-?(\d{1,3})(\.\d{1,20})?$/
    return regex.test(longitude)
}

function validateLatitude(latitude) {
    // 使用正则表达式验证纬度
    var regex = /^-?(\d{1,2})(\.\d{1,20})?$/
    return regex.test(latitude)
}

function validateCoordinates(coordinates) {
    // 使用正则表达式验证经纬度
    if (isNotEmpty(coordinates)) {
        if (coordinates.includes(',')) {
            var lnglats = coordinates.split(',')
            if (validateLongitude(lnglats[0]) && validateLatitude(lnglats[1])) {
                return true
            }
        }
    }

    return false
}

// echarts加载动画配置
function echartsLoading() {
    return { maskColor: 'rgba(255, 255, 255, 0.3)', lineWidth: 2 }
}

// 将手机号中间四位替换为星号
function hidePhoneNumber(phoneNumber) {
    let result = ''
    if (isNotEmpty(phoneNumber)) {
        // 使用正则表达式将手机号的中间四位替换为星号
        result = phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }
    return result
}

function getTimeTypeByIndex(index) {
    if (isNotEmpty(index)) {
        var ind = index + ''
        var result = 'last12month'
        switch (ind) {
            case '1':
                result = 'last24hour'
                break
            case '2':
                result = 'last7day'
                break
            case '3':
                result = 'last30day'
                break
            case '4':
                result = 'last12month'
                break
        }
        return result
    }
}

function getHistoryXDataByTimeType(timeVal, timeType) {
    var result = ''
    switch (timeType) {
        case 'last24hour':
            result = timeVal.substring(11, 16)
            break
        case 'last12month':
            result = timeVal.substring(2, 7)
            break
        case 'last30day':
        case 'last7day':
            result = timeVal.substring(5, 10)
            break
    }
    return result
}

function getDevicePropValue(propInfo, useRealValue = false) {
    let value = ''
    if (isNotEmpty(propInfo)) {
        switch (propInfo.dataType) {
            case 'datetime':
                value = propInfo.value
                break
            case 'enum':
                value = useRealValue ? propInfo.realValue : propInfo.value
                break
            case 'base64':
                value = propInfo.value
                break
            default:
                value = isNotEmpty(propInfo.value) ? (propInfo.value.length > 20 ? propInfo.value.substring(0, 20) + '...' : String(propInfo.value)) : ''
                break
        }
        // 设备状态为离线时，显示*号
        // value = propInfo.state === 3 && isEmpty(value) ? '*' : value
    }
    value = typeof value === 'string' ? value.trim() : value
    return value || ''
}

// 获取格式化后的属性值
function getPropValueLastFormat(prop, withUnit = false) {
    let value = getDevicePropValue(prop)
    let realValue = withUnit && isNotEmpty(prop.unit) ? value + ' ' + prop.unit : value
    return isEmpty(value) ? '-' : realValue
}

function getChartMaxNum(arr, scale = 1) {
    return Math.ceil(Math.max(...arr) * scale)
}

function getChartMinNum(arr, scale = 1) {
    return Math.floor(Math.min(...arr) * scale)
}

// 获取前一个月及近12个月日期 格式yy-mm
function getPreviousMonths(count) {
    const today = new Date()
    const months = []

    for (let i = 0; i < count; i++) {
        const month = today.getMonth() - 1 - i
        const year = today.getFullYear() - Math.floor((today.getMonth() + i) / 12)

        const monthFormatted = String(month < 0 ? month + 12 : month + 1).padStart(2, '0')
        const yearFormatted = String(year).slice(2)

        months.push(`${yearFormatted}/${monthFormatted}`)
    }
    return months.reverse()
}

// 切换风格主题
function clearDarkTheme(theme) {
    // 设置深色系
    store.commit('admin/layout/updateLayoutSetting', { key: 'siderTheme', value: theme })
    store.commit('admin/layout/updateLayoutSetting', { key: 'headerTheme', value: theme })
    document.getElementsByTagName('body')[0].classList.remove('ivu-theme-dark')
}

function XMLtoString(elem) {
    var serialized
    var serializer
    try {
        // XMLSerializer exists in current Mozilla browsers
        serializer = new XMLSerializer()
        serialized = serializer.serializeToString(elem)
    } catch (e) {
        // Internet Explorer has a different approach to serializing XML
        serialized = elem.xml
    }
    return serialized
}

export default {
    getArrData,
    isEmpty,
    isNotEmpty,
    cloneData,
    checkJson,
    queryUrlParams,
    objToLowerCase,
    dataIsNull,
    modalClientStyle,
    ArrayisEquals,
    validateName,
    msgError,
    dataTrim,
    escapeHtml,
    deleteRecord,
    setFullScreen,
    bdToGeoLngLat,
    geoToBdLnglat,
    triggerWindowResizeEvent,
    isIE,
    generateRandomStr,
    statusMap,
    messageTypeMap,
    messageLevelMap,
    AssetStatusMap,
    getOrderLevelText,
    getOrderState,
    JsonParse,
    loadJs,
    base64ToFile,
    uuid4,
    uuid8,
    uuid16,
    groupBy,
    getValueLabelName,
    getNumberOfDays,
    dateTimeFormat,
    getDay,
    pageJump,
    getSignalrGroup,
    closeSignalr,
    getMessageContent,
    getPlaceAddress,
    handleFormatErrorImg,
    handleFormatErrorXlsx,
    handleFormatErrorDll,
    handleFormatErrorMedia,
    handleFormatError,
    handleMaxSize,
    handleMaxSize100,
    formatMessageOrderData,
    uploadWorkOrderImg,
    formatMessageTable,
    formatDate,
    getMessageDataPageAndVideo,
    getStrFullLength,
    getJobStatus,
    isFloat,
    getEventType,
    getTenantKeyByPath,
    convertTo2DArray,
    echartsLoading,
    hidePhoneNumber,
    getDevicePropValue,
    getPropValueLastFormat,
    validateSelect,
    validateTime,
    getWeekDateArrStr,
    getWeekDateStr,
    getPropValueToFixed,
    updateChartData,
    delay,
    removeEmptyProperties,
    validatePhoneNumber,
    validateEmail,
    validateCoordinates,
    getTimeTypeByIndex,
    getHistoryXDataByTimeType,
    getChartMaxNum,
    getChartMinNum,
    getPreviousMonths,
    clearDarkTheme,
    XMLtoString
}
